﻿using System;
using System.IO;
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace Server.Utils
{
    public class LogUtil
    {
        static volatile ILoggerFactory _instance = null;
        static readonly object Padlock = new object();

        /// <summary>
        /// 获取单一实例
        /// </summary>
        /// <returns></returns>
        public static ILoggerFactory GetILoggerFactory()
        {
            if (_instance == null)
            {
                lock (Padlock)
                {
                    if (_instance == null)
                    {
                        _instance = LoggerFactory.Create(builder =>
                        {
                            builder.AddConsole();
                            builder.AddDebug();
                            builder.AddFile();
                        });
                    }
                }
            }
            return _instance;
        }


        public static void LogInfo(string message)
        {
            var _logger = LogUtil.GetILoggerFactory().CreateLogger("application");
            _logger.LogInformation(message);
        }

        public static void LogError(string message)
        {
            var _logger = LogUtil.GetILoggerFactory().CreateLogger("application");
            _logger.LogInformation(message);
        }

        public static void LogWarning(string message)
        {
            var _logger = LogUtil.GetILoggerFactory().CreateLogger("application");
            _logger.LogWarning(message);
        }

        /// <summary>
        ///  构建请求request
        /// </summary>
        /// <returns></returns>
        public static string BuildRequetLog(HttpRequest request, string title)
        {
            string contentFromBody;
            using (var reader = new StreamReader(request.Body))
            {
                contentFromBody = reader.ReadToEnd();
            }

            string str = request.Path + "："; // +  + "," + title + "：params：" + request.QueryString + ",Body：" + contentFromBody;
            str += "methos：" + request.Method;
            if (!string.IsNullOrEmpty(title))
            {
                str += ",title：" + title;
            }
            if (!string.IsNullOrEmpty(value: request.QueryString.ToString()))
            {
                str += $",params：{request.QueryString}";
            }
            if (!string.IsNullOrEmpty(contentFromBody))
            {
                str += ",body：" + contentFromBody;
            }
            string token = request.Headers["token"].ToString();
            if (!string.IsNullOrEmpty(token))
            {
                str += ",memberId：" + (JwtUtil.GetMemberIdFromToken(token) ?? "");
                str += ",createTime：" + (JwtUtil.GetEexpires(token).ToString("yyyy-MM-dd HH:mm:ss") ?? "");
            }
            str += ",platform：" + (request.Headers["platform"].ToString());
            return str;
        }
    }
}
